var MerchantPage=React.createClass({
	getInitialState:function(){
		return {
			level:0,
			merchantId:"", //二级页面所需的商家id
			goodId:"" //三级页面所需的商品id
		};

	},
	changeLevel:function(l,id){
		if(l==0){
			this.setState({
				level:l
			});
		}else if(l==1){
			this.setState({
				level:l,
				merchantId:id||this.state.merchantId
			});
		}else if(l==2){
			this.setState({
				level:2,
				goodId:id
			});
		}

	},
	render:function(){
		var toDisplay;
		switch (this.state.level){
			case 0:
				toDisplay=<MerchantFrontPage changeLevel={this.changeLevel}/>;
				break;
			case 1:
				toDisplay=<MerchantDetailPage merchantId={this.state.merchantId} changeLevel={this.changeLevel}/>;//商家详情
				break;
			case 2:
				toDisplay=<GoodDetailPage goodId={this.state.goodId} merchantId={this.state.merchantId} changeLevel={this.changeLevel}/>;//商品详情
				break;

		}
		return (
			<div>
				{toDisplay}
			</div>
			
			);

	}
});
/*************************商家首页***********************/
var MerchantFrontPage=React.createClass({
	getInitialState:function(){
		return{
			merchants_time:null,
			merchants_sale:null,
			loaded_time:0,//表示当前已经抓取了多少个按时间排序的数据
			loaded_sale:0,//表示当前已经抓取了多少个按销量排序的数据
			sortBy:"time"
		};
	},
	componentDidMount:function(){
		//获取按时间排序的数据
	  $.ajax({
	    url:config.api.getMerchants[0],
	    type:"GET",
	    data:{
	    	sort:0
	    },
	    success:function(d){
	    	console.log(d);
	    	this.setState({
	    		merchants_time:d.merchants,
	    		loaded_time:this.state.loaded_time+d.merchants.length
	    	});
	    }.bind(this),
	    error:function(){
	      alert("获取数据出错");
	    }
	  });
	  //获取按销量排序的数据
	  $.ajax({
	    url:config.api.getMerchants[0],
	    type:"GET",
	    data:{
	    	sort:1
	    },
	    success:function(d){
	    	console.log(d);
	    	this.setState({
	    		merchants_sale:d.merchants,
	    		loaded_sale:this.state.loaded_sale+d.merchants.length
	    	});
	    }.bind(this),
	    error:function(){
	      alert("获取数据出错");
	    }
	  });
	},
	//修改排序方式
	changeSortType:function(type){
		this.setState({
			sortBy:type
		});
	},
	render:function(){
		var content=null;
		if(this.state.loaded_time&&this.state.loaded_sale){
			switch(this.state.sortBy){
				case "time":
				content=<MerchangtList data={this.state.merchants_time} changeLevel={this.props.changeLevel}/>;
				break;
				case "sale":
				content=<MerchangtList data={this.state.merchants_sale} changeLevel={this.props.changeLevel}/>;
				break;
			}
		}else{
			content=<p>尚未有商家入驻</p>;
		}
		return (
			<div id="MerchantFrontPage">
				<MerchantToolBar sortBy={this.state.sortBy} changeSortType={this.changeSortType}/>
				{content}
			</div>
			);

	}
});
var MerchantToolBar=React.createClass({
	sortByTime:function(){
		this.props.changeSortType("time");
	},
	sortBySale:function(){
		this.props.changeSortType("sale");
	},
	render:function(){
		return (
			<div id="MerchantToolBar">
				<div className={this.props.sortBy=="time"?"sortType active":"sortType"} id="sortByTime" onClick={this.sortByTime}>
					<span>按入驻时间</span>
				</div>
				<div className={this.props.sortBy=="sale"?"sortType active":"sortType"} id="sortBySale" onClick={this.sortBySale}>
					<span>按销量</span>
				</div>
				<div className="searchBox">
					<button id="searchBtn" className="btn btn-primary">搜索</button>
					<input id="searchInput" type="text" placeholder=" 搜索商家"/>
				</div>
			</div>
			);
	}
});
var MerchangtList=React.createClass({
	toMerchantDetail:function(e){
		var $target=$(e.target);
		var merchantId;
		if($target.hasClass("MerchangtListItem")){
			merchantId=$target.data("id");
		}else{
			merchantId=$target.closest(".MerchangtListItem").data("id");
		}
	    this.props.changeLevel(1,merchantId);
	},
	render:function(){
		var self=this;
		var list=this.props.data.map(function(one){
				return (
					<MerchangtListItem clickHandler={self.toMerchantDetail} avatarUrl={one.avatarUrl} name={one.name} phone={one.phone} goodImage={one.goodImage} id={one.merchantId}/>
					);
			});
		return (
			<ul id="MerchangtList">
				{list}
			</ul>
			);
	}
});
var MerchangtListItem=React.createClass({
	render:function(){
		return (
			<li className="MerchangtListItem" data-id={this.props.id} onClick={this.props.clickHandler}>
				<div className="MerchantInfoBox">
					<img src={this.props.avatarUrl}/>
					<h5>{this.props.name}</h5>
					<h5>电话:{this.props.phone}</h5>
				</div>
				<div className="GoodsBox">
					{
						this.props.goodImage.map(function(url){
							return (
								<img src={url} className="goodImage"/>
								);
						})
					}
				</div>
			</li>
			);
	}
});
/*************************商家详情***********************/
var MerchantDetailPage=React.createClass({
	goToFrontPage:function(e){
		this.props.changeLevel(0);
	},
	render:function(){
		return (
			<div id="MerchantDetailPage">
				<ul className="breadcrumb" >
					<li className="withDivider" onClick={this.goToFrontPage}>画材选购</li>
					<li>商家详情</li>
				</ul>
				<MerchantDetailInfoBox merchantId={this.props.merchantId}/>
				<MerchantDetailToolBar/>
				<GoodsTable merchantId={this.props.merchantId} changeLevel={this.props.changeLevel}/>
			</div>
			);
	}

});
var MerchantDetailInfoBox=React.createClass({
	getInitialState:function(){
		return {
			info:null,
			loaded:false
		};
	},
	componentDidMount:function(){
	  $.ajax({
	    url:config.api.getMerchantDetail[0].replace(/\<\w+\>/,this.props.merchantId),
	    type:"GET",
	    success:function(d){
	       console.log(d);
	       this.setState({
	       	info:d.merchant,
	       	loaded:true
	       });
	    }.bind(this),
	    error:function(){
	      alert("获取数据出错");
	    }
	  });
	},
	render:function(){
		if(this.state.loaded){
			return (
				<div id="MerchantDetailInfoBox">
					<div className="InfoBoxhead">
						<img src={this.state.info.avatarUrl} alt=""/>
						<div className="InfoBoxhead_text">
							<h4>{this.state.info.name}</h4>
							<h4>电话:{this.state.info.phone}</h4>
						</div>
						<div id="tips">代购请直接拨打电话哦</div>
					</div>
					<p className="infoBoxContent">
						{this.state.info.description}
					</p>
				</div>
				);
		}else{
			return (
				<p>商家信息加载中</p>
				);
		}

	}

});
var MerchantDetailToolBar=React.createClass({
	render:function(){
		return (
			<div id="MerchantDetailToolBar">
				<div className="goodsFilter" id="newestGoods" >
					<span>最新上架</span>
				</div>
				<div className="goodsFilter" id="allGoods" >
					<span>全部商品</span>
				</div>
			</div>
			);
	}
});
var GoodsTable=React.createClass({
	getInitialState:function(){
		return {
			goods:null,
			loaded:false
		};
	},
	componentDidMount:function(){
	  $.ajax({
	    url:config.api.getMerchantGoods[0].replace(/\<\w+\>/,this.props.merchantId),
	    type:"GET",
	    success:function(d){
	       console.log(d);
	       this.setState({
	       	goods:d.goods,
	       	loaded:true
	       });
	    }.bind(this),
	    error:function(){
	      alert("获取数据出错");
	    }
	  });
	},
	limitFloat:function(f){
		var str=f+"";
		var index=str.indexOf(".");
		return str.substring(0,index+2);
	},
	goToGoodDetail:function(e){
		var $target=$(e.target);
		var goodId;
		if($target.hasClass("singleGood")){
			goodId=$target.data("goodid");
		}else{
			goodId=$target.closest(".singleGood").data("goodid");
		}
		this.props.changeLevel(2,goodId);//跳转到商品详情页
	},
	render:function(){
		if(this.state.loaded){
			var goodsList=[];
			var row=[];
			for(var i=0,len=this.state.goods.length;i<len;i++){
				if(i%5==0&&i!=0){
					goodsList.push(
						<div className="GoodsRow">
							{row}
						</div>
					);
					row=[];
				}
				row.push(
					<div className="singleGood" data-goodid={this.state.goods[i].goodId} onClick={this.goToGoodDetail}>
						<img src={this.state.goods[i].image} alt=""/>
						<h4 className="discountPrice">￥{this.limitFloat(this.state.goods[i].price*this.state.goods[i].discount)}</h4>
						<h5 className="originalPrice">￥{this.limitFloat(this.state.goods[i].price)}</h5>
						<p className="goodTitle">{this.state.goods[i].title}</p>
					</div>
					);
				if(i==len-1&&goodsList.length==0){
					goodsList.push(
						<div className="GoodsRow">
							{row}
						</div>
					);
				}
			}
			console.log(goodsList);
			return (
				<div id="GoodsTable">
					{goodsList}
				</div>
				);

		}else{
			return (
				<div id="GoodsTable">
					<p>商品列表加载中</p>
				</div>
				);
		}

	}
});
/***********************************商品详情页********************************/
//需要传入goodId,changeLevel方法
var GoodDetailPage=React.createClass({
	getInitialState:function(){
		return {
			good:null,
			goodDataLoaded:false,
			merchant:null,
			merchantDataLoaded:false
		};
	},
	componentDidMount:function(){
	  $.ajax({
	    url:config.api.getGoodDetail[0].replace(/\<\w+\>/,this.props.goodId),
	    type:config.api.getGoodDetail[1],
	    success:function(d){
	       console.log(d);
	       this.setState({
	       	good:d.good,
	       	goodDataLoaded:true
	       });
	    }.bind(this),
	    error:function(){
	      alert("获取数据出错");
	    }
	  });
	  $.ajax({
	    url:config.api.getMerchantDetail[0].replace(/\<\w+\>/,this.props.merchantId),
	    type:config.api.getMerchantDetail[1],
	    success:function(d){
	       console.log(d);
	       this.setState({
	       	merchant:d.merchant,
	       	merchantDataLoaded:true
	       });
	    }.bind(this),
	    error:function(){
	      alert("获取数据出错");
	    }
	  });
	},
	goToFrontPage:function(){
		this.props.changeLevel(0);
	},
	goToMerchantPage:function(){
		this.props.changeLevel(1);
	},
	render:function(){
		if(this.state.goodDataLoaded&&this.state.merchantDataLoaded){
			return (
				<div id="GoodDetailPage">
					<ul className="breadcrumb" >
						<li className="withDivider" onClick={this.goToFrontPage}>画材选购</li>
						<li className="withDivider" onClick={this.goToMerchantPage}>商家详情</li>
						<li >商品详情</li>
					</ul>
					<GoodDetailInfoBox good={this.state.good} merchant={this.state.merchant}/>
					<img className="big_img_good" src={this.state.good.bigImage} alt="商品大图"/>
				</div>
			);
		}else{
			return (
				<div id="GoodDetailPage">
					<ul className="breadcrumb" >
						<li className="withDivider" onClick={this.goToFrontPage}>画材选购</li>
						<li className="withDivider" onClick={this.goToMerchantPage}>商家详情</li>
						<li >商品详情</li>
					</ul>
					<p>商品详情加载中</p>
				</div>
			);
		}

	}
});	
var GoodDetailInfoBox=React.createClass({
	limitFloat:function(f){
		var str=f+"";
		var index=str.indexOf(".");
		return str.substring(0,index+2);
	},
	render:function(){
		var data=this.props.good;
		return (
			<div id="GoodDetailInfoBox">
				<GoodImageCarousel images={data.images}/>
				<div id="GoodDetailText">
					<div id="GoodDetailText_section1">
						<h3 className="discountPrice ">￥{this.limitFloat(data.price*data.discount)} <span className="originalPrice ">￥{this.limitFloat(data.price)}</span></h3>
						<h4 className="goodTitle ">{data.title}</h4>
						<div id="merchantCard">
							<img src={this.props.merchant.avatarUrl} alt="" className="merchantAvatar "/>
							<div>
								<p className="merchantName ">{this.props.merchant.name}</p>
								<p className="merchantPhone ">电话:{this.props.merchant.phone}</p>
							</div>
						</div>

					</div>
					<p className="goodDescription ">{data.description}</p>
					
					
				</div>
				<div id="tips">代购请直接拨打电话哦</div>
			</div>
			);
	}
});	
var GoodImageCarousel=React.createClass({
	getInitialState:function(){
		if(this.props.images.length<=4){
			return {
				beginIndex:0,
				endIndex:this.props.images.length-1,
				activeIndex:0
			};
		}else{
			return {
				beginIndex:0,
				endIndex:3,
				activeIndex:0
			};
		}
	},
	setActiveIndex:function(e){
		var index=$(e.target).data("slide-to");
		this.setState({
			activeIndex:index
		});
	},
	increaseActiveIndex:function(){
		var newActiveIndex=this.state.activeIndex+1;
		if(newActiveIndex>=this.props.images.length){
			newActiveIndex=this.props.images.length-1;
		}
		if(newActiveIndex>this.state.endIndex){
			this.nextPage();//翻页
		}
		this.setState({
			activeIndex:newActiveIndex
		});
	},
	decreaseActiveIndex:function(){
		var newActiveIndex=this.state.activeIndex-1;
		if(newActiveIndex<0){
			newActiveIndex=0;
		}
		if(newActiveIndex<this.state.beginIndex){
			this.prevPage();//翻页
		}
		this.setState({
			activeIndex:newActiveIndex
		});
	},
	nextPage:function(){
		var endIndex_new=this.state.endIndex+4;
		if(endIndex_new>=this.props.images.length){
			endIndex_new=this.props.images.length-1;
		}//限制
		var increcement=endIndex_new-this.state.endIndex;
		this.setState({
			beginIndex:this.state.beginIndex+increcement,
			endIndex:endIndex_new
		});
	},
	prevPage:function(){
		var beginIndex_new=this.state.beginIndex-4;
		if(beginIndex_new<0){
			beginIndex_new=0;
		}//限制
		var decrecement=beginIndex_new-this.state.beginIndex;
		this.setState({
			beginIndex:beginIndex_new,
			endIndex:this.state.endIndex+decrecement
		});
	},
	render:function(){
		var indicatorItems=[];
		var images=this.props.images;
		for(var i=this.state.beginIndex;i<=this.state.endIndex;i++){
			indicatorItems.push(
				<li>
					<img src={images[i]} alt="" data-target="#GoodImageCarousel" data-slide-to={i} onClick={this.setActiveIndex}/>
				</li>
				);
		}
		var first=true;
		return (
			<div id="carouselContainer">
				<div id="GoodImageCarousel" className="carousel slide">
					   <div className="carousel-inner">
					   	{
					   		images.map(function(image){
					   			if(first){
					   				first=false;
					   				return (
					   					<div className="item active">
					   					   <img src={image} alt="good_imgs"/>
					   					</div>
					   					);

					   			}else{
					   				return (
					   					<div className="item">
					   					   <img src={image} alt="good_imgs"/>
					   					</div>
					   					);
					   			}

					   		})
					   	}
					   </div>
				</div>	
				<div className="carouselControl">
					<ol className="indicator">
						{indicatorItems}
					</ol>

					<a className="prevSlide" href="#GoodImageCarousel" 
					  data-slide="prev" onClick={this.decreaseActiveIndex}>
					  <img src="../../image/prevSlide.png"/>
					</a>
					<a className="nextSlide" href="#GoodImageCarousel" 
					    data-slide="next" onClick={this.increaseActiveIndex}>
					  <img src="../../image/nextSlide.png"/>
					</a>
				</div>
			</div>
			);
	}
});
